package com.trxy.shiro.realm;

import com.trxy.model.User;
import com.trxy.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


@Component
public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;

    public UserRealm() {
        System.out.println("UserRealm被创建了");
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行授权.............");
        //如果user是xiaoming， 给他 Teacher
        //如果user是Tom，  给他 Student
        String name = (String) principals.getPrimaryPrincipal();

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        List<String> permissionList = new ArrayList<String>();//本系统暂时没使用permission控制
        info.addStringPermissions(permissionList);//对于需要permission控制的项目来说，这里则需要计算出具体的permissionList

        if (name.equals("xiaoming")) {
            info.addRole("SuperAdmin");
        } else {
            info.addRole("Admin");
        }
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行 认证  @@@@@@@@@@@@@@@@@@@@@");
        UsernamePasswordToken token2 = (UsernamePasswordToken) token;
        String name = token2.getUsername();
        String password = new String(token2.getPassword());

        User user = userService.selectByName(name);
        if (user == null) {
            throw new UnknownAccountException("这是一个无用户的异常");
        } else {
            User user2 = userService.selectByNameAndPassword(name, password);
            if (user2 == null) {//如果没查到，就主动抛出UnknownAccountException
                throw new AuthenticationException("这是一个认证异常");
            } else {
                return new SimpleAuthenticationInfo (token.getPrincipal (), token.getCredentials (), this.getName ());
            }
        }
    }
}
